
$(function () {
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true
    });

    if ($('#form_content').length) {
        contentObj = CKEDITOR.replace('form_content');
    }


});

/**
 * summernote 自定义文件上传
 * @param {type} file
 * @returns {undefined}
 */
function sendFile(file, sumObj) {
    //console.log(eee);
    //return ;
    $(".note-toolbar").append('<span class="note-alarm">正在上传图片</span>');
    var filename = false;
    try {
        filename = file['name'];
    } catch (e) {
        filename = false;
    }
    if (!filename) {
        $(".note-alarm").remove();
    }
    //以上防止在图片在编辑器内拖拽引发第二次上传导致的提示错误
    var ext = filename.substr(filename.lastIndexOf("."));
    ext = ext.toUpperCase();
    var timestamp = new Date().getTime();
    var name = timestamp + "_" + $(sumObj).attr('aid') + ext;
    //name是文件名，自己随意定义，aid是我自己增加的属性用于区分文件用户
    data = new FormData();
    data.append("file", file);
    data.append("key", name);
    data.append("token", $(sumObj).attr('token'));
    $.ajax({
        data: data,
        type: "POST",
        url: "/common/upoladImage",
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            //data是返回的hash,key之类的值，key是定义的文件名
            $(".note-alarm").html("上传成功,请等待加载");
            setTimeout(function () {
                $(".note-alarm").remove();
            }, 3000);
            //alert(data.data);
            console.log(data);
            $(sumObj).summernote(
                    'insertImage',
                    data.msg,
                    function ($image) {
                        $image.css('width', '100%');
                        $image.attr('data-filename', 'retriever');
                    }
            );
        },
        error: function () {
            $(".note-alarm").html("上传失败");
            setTimeout(function () {
                $(".note-alarm").remove();
            }, 3000);
        }
    });
}

/**
 * 显示模态框
 * @param {type} title
 * @param {type} txt
 * @param {type} waiting
 * @returns {undefined}
 */
function toast(title, txt, waiting) {
    $("#modal-msg-title").text(title);
    $("#modal-msg-content").text(txt);
    $("#modal-msg").modal('show');
    setTimeout(function () {
        $('#modal-msg').modal('hide');
    }, waiting);
}

/**
 * 改变数据状态
 * @param {type} img
 * @param {type} status
 * @param {type} url
 * @returns {undefined}
 */
function updateStatus(img, status, url) {
    stbAjax(url, {status: status}, function (data) {
        console.log(data);
        toast(data.msg || data.info, data.msg || data.info, 1000);
        if (data.status == 200) {
            setTimeout('location.reload()', 1000);
        }
    });
}

/**
 * 自定义AJAX
 * @param {type} url
 * @param {type} data
 * @param {type} fun
 * @param {type} method
 * @returns {undefined}
 */
function stbAjax(url, data, fun, method) {
    var method = method || 'post';
    $.ajax({
        data: data,
        type: method,
        url: url,
        success: fun,
        error: function () {
            toast('失败', '服务器请求错误', 3000);
        }
    });
}

/**
 * ajax上传图片
 * @param {type} file
 * @param {type} cb
 * @returns {undefined}
 */
function ajaxFile(file, cb) {
    data = new FormData();
    var timestamp = new Date().getTime();
    data.append("file", file);
    data.append("key", timestamp);
    $.ajax({
        data: data,
        type: "POST",
        url: "/admin.php/common/upoladImage",
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $("#modal-msg-title").text('图片上传');
            $("#modal-msg-content").text('图片上传中，请稍等...');
            $("#modal-msg").modal('show');
        },
        success: cb,
        error: function () {
            toast(data.msg || data.info, data.msg || data.info, 1000);
        }
    });
    $("#modal-msg").modal('hide');
}

/**
 * 自定义confirm模态框
 * @param {type} params
 * @returns {undefined}
 */
function stbConfirm(params) {
    var model = $("#stb_confirm_model");
    model.find(".title").html(params.title);
    model.find(".message").html(params.message);

    $("#common_confirm_btn").click();
    //每次都将监听先关闭，防止多次监听发生，确保只有一次监听
    $("#stb_confirm_cancel").unbind("click");
    $("#stb_confirm_ok").unbind("click");

    model.find(".ok").bind("click", function () {
        params.operate(true);
    });

    model.find(".cancel").bind("click", function () {
        params.operate(false);
    });
    model.modal('show');
}

/**
 * 删除信息前提示
 * @param {type} url
 * @param {type} msg
 * @returns {undefined}
 */
function confirmDelDefault(url, msg) {
    stbConfirm({
        title: "确认提示",
        message: msg,
        operate: function (reselt) {
            if (reselt) {
                stbAjax(url, {}, function (data) {
                    console.log(data);
                    toast(data.msg || data.info, data.msg || data.info, 1000);
                    if (data.code == 1) {
                        setTimeout('location.reload()', 1000);
                    }
                }, 'get');
            } else {
            }
        }
    });
}

/**
 * 更新缓存
 * @param {type} project
 * @returns {undefined}
 */
function refresh(project) {
    stbAjax('/admin.php/common/refresh', {project: project}, function (data) {
        console.log(data);
        toast(data.msg || data.info, data.msg || data.info, 1000);
        if (data.code) {
            setTimeout('location.reload()', 1000);
        }
    }, 'post');
}

/**
 * 单图片上传前预览
 * @param {type} file
 * @param {type} imgEl
 * @param {type} logBox
 * @returns {undefined}
 */
function previewImgOne(file, imgEl, logBox) {
    var reader = new FileReader();

    //读取文件过程方法
    reader.onloadstart = function (e) {
        logBox.innerHTML = "开始读取....";
    };
    reader.onprogress = function (e) {
        logBox.innerHTML = "正在读取中....";
    };
    reader.onabort = function (e) {
        logBox.innerHTML = "中断读取....";
    };
    reader.onerror = function (e) {
        logBox.innerHTML = "读取异常....";
    };
    reader.onload = function (e) {
        logBox.innerHTML = "成功读取....";
        imgEl.src = e.target.result;
        //或者 img.src = this.result;  //e.target == this
    };
    reader.readAsDataURL(file);
}

/**
 * 重置表单
 * @param {type} formid
 * @returns {undefined}
 */
function fromReset(formid) {
    $("#" + formid).find("input").not(':button, :submit, :reset').val('').removeAttr('checked');
    $("#" + formid).find("select").val('');
    $("#" + formid).find("textarea").val('');
}
/**
 * 更新排序
 * @param {type} url
 * @returns {undefined}
 */
function setOrder(url) {
    console.log(url);
    var order = {};
    $('input.list_order').each(function () {
        order[$(this).attr('data-id')] = this.value;
    });

    stbAjax(url, {list_order: order}, function (data) {
        console.log(data);
        toast(data.msg || data.info, data.msg || data.info, 1000);
        if (data.code == 1) {
            setTimeout('location.reload()', 1000);
        }
    });

}

/**
 * 上传封面图片
 * @param {type} fileInput
 * @returns {undefined}
 */
function upThumbImg(fileInput) {
    var file = $(fileInput)[0].files[0];
    if (file === undefined) {
        return false;
    }
    //console.log($(fileInput));
    ajaxFile(file, function (response) {
        console.log(response);
        if (response.code === 1) {
            $('#admin_thumb_input').val(response.msg);
            $('#admin_thumb_img').attr('src', response.msg);
        } else {
            toast('图片上传失败', response.msg, 2000);
        }
    });
}

/**
 * 上传普通文件[并指定input存放返回的文件地址]
 * @param {type} fileInput
 * @param {type} inputTextId
 * @returns {Boolean}
 */
function upAdminFile(fileInput, inputTextId) {
    var file = $(fileInput)[0].files[0];
    if (file === undefined) {
        return false;
    }
    ajaxFile(file, function (response) {
        console.log(response);
        if (response.code === 1) {
            $('#' + inputTextId).val(response.msg);
        } else {
            toast('文件上传失败', response.msg, 2000);
        }
    });
}

/**
 * 预览上传文件[图片]
 * @param {type} inputTextId
 * @returns {undefined}
 */
function previewAdminFile(inputTextId, path) {
    if (inputTextId) {
        var imgPath = $('#' + inputTextId).val();
    } else {
        var imgPath = path;
    }
    if (!imgPath) {
        return false;
    }
    $('#preview_admin_file_img').attr('src', imgPath);
    $("#preview_admin_file_model").modal('show');
}

/*多文件上传 start*/

/**
 * 多文件上传选择文件
 * @param {type} boxId
 * @param {type} btnObj
 * @param {type} inputFileId
 * @returns {undefined}
 */
function multiSelectFile(boxId, btnObj, inputFileId) {
    console.log(boxId);
    $('#' + boxId + ' .fa-file').removeClass('active');
    $(btnObj).addClass('active');
    $('#' + inputFileId).click();
}
/**
 * 增加一个文件
 * @param {type} javascriptTemplateId
 * @param {type} addBtnBoxId
 * @returns {undefined}
 */
function addMultiHtml(javascriptTemplateId, addBtnBoxId) {
    var html = $('#' + javascriptTemplateId).html();
    $("#" + addBtnBoxId).before(html);
}

/**
 * 文件上传
 * @param {type} fileInput
 * @param {type} boxId
 * @returns {Boolean}
 */
function multiUploadFile(fileInput, boxId) {
    var file = $(fileInput)[0].files[0];
    if (file === undefined) {
        return false;
    }
    ajaxFile(file, function (response) {
        if (response.code === 1) {
            $('#' + boxId + ' .active').parent('div').siblings('div.formMulti_path').children('input').val(response.msg);
        } else {
            toast('文件上传失败', response.msg, 2000);
        }
    });
}

/**
 * 多图上传图片预览
 * @param {type} prevInput
 * @returns {undefined}
 */
function previewAdminMultiFile(prevInput) {
    var imgPath = $(prevInput).parent('div').siblings('div.formMulti_path').children('input').val();
    if (!imgPath) {
        return false;
    }
    $('#preview_admin_file_img').attr('src', imgPath);
    $("#preview_admin_file_model").modal('show');
}

/**
 * 删除文件
 * @param {type} iElement
 * @returns {undefined}
 */
function delAdminMultiFile(iElement) {
    $(iElement).parent('div').parent('div.row').remove();
}